package com.fingard.dsp.bank.directbank.bojz01;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class BOJZ01BatPayRec extends BOJZ01Base implements IBatPayRec {
    //1988
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    //9188
    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    //批量代收和代发工资提交
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        try {
            // 198801 批量代付05B2EBankInnerBatchTransfer 198802 代发工资05B2EAgentPaySalary
            if (p_reqBat.reqHeader.transType.equals("1988")) {
                if ("1".equals(p_reqBat.sameBnk)) {//批量转账（同行）
                    transCode = "B2EBatchInnerTransfer";
                } else if ("0".equals(p_reqBat.sameBnk)) {////批量转账（跨行）
                    transCode = "B2EBatchTransfer";
                }
            }
            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter, "0");
            /*<Body>
            <PayerAcNo>521012735403012</PayerAcNo>
			<PayerAcName></PayerAcName>
			<TotalAmount>22</TotalAmount>
			<TotalCount>2</TotalCount>
			<List>
			<Map>
			<PayeeAcNo>0402024409300161221</PayeeAcNo>
			<PayeeAcName>800003208</PayeeAcName>
			<Amount>10.00</Amount>
			<Remark></Remark>
			</Map>
			</List>
			</Body>
			</Message>*/
            xmlWriter.writeStartElement("Body");
            xmlWriter.writeElementString("PayerAcNo", p_reqBat.ownAct);
            StringBuffer sbMsg = new StringBuffer();
            if (Integer.parseInt(p_reqBat.totalNum) <= 2000) {
                xmlWriter.writeElementString("TotalCount", p_reqBat.totalNum);
            } else {
                retAts.respCode = "0";
                retAts.respInfo = "批量支付最大支持总笔数不能超过2000笔";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = ConnState.FAIL;
                retAts.writeRetToATS();
                return retAts;
            }
            xmlWriter.writeElementString("TotalAmount", p_reqBat.totalAmt);
            xmlWriter.writeElementString("CifJnlNo", reqHeader.reqSeqID);
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            while (p_reqBat.readRecord()) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("isLargeAmt", p_reqBat.readedDetail.isLargeAmt());
                map.put("paySpd", p_reqBat.readedDetail.paySpd);
                map.put("PayeeAcNo", p_reqBat.readedDetail.recAct);
                map.put("PayeeAcName", p_reqBat.readedDetail.recName);
                map.put("Amount", p_reqBat.readedDetail.payAmount);
                map.put("Remark", p_reqBat.readedDetail.abstractATS);
                map.put("Use", p_reqBat.readedDetail.purpose);
                map.put("UnionDeptId", p_reqBat.readedDetail.cnapsCode);
                map.put("PayeeBankName", p_reqBat.readedDetail.cnapsName);
                list.add(map);
            }
            if ("0".equals(p_reqBat.sameBnk)) {
                String trsMode = "1";//默认人行大小额 暂不支持网银互联的方式
                xmlWriter.writeElementString("Remit", trsMode);////1-大额2-网银互联
            }
            xmlWriter.writeStartElement("List");
            int count = 0;
            for (int i = 0; i < list.size(); i++) {
                count++;
                xmlWriter.writeStartElement("Map");
                xmlWriter.writeElementString("PayeeAcNo", (String) list.get(i).get("PayeeAcNo"));
                xmlWriter.writeElementString("PayeeAcName", (String) list.get(i).get("PayeeAcName"));
                xmlWriter.writeElementString("Amount", (String) list.get(i).get("Amount"));
                xmlWriter.writeElementString("Remark", (String) list.get(i).get("Remark"));//传入对账码
                xmlWriter.writeElementString("Use", (String) list.get(i).get("Use"));
                xmlWriter.writeElementString("TraceNo", String.valueOf(count));
                if ("0".equals(p_reqBat.sameBnk)) {
                    xmlWriter.writeElementString("UnionDeptId", (String) list.get(i).get("UnionDeptId"));
                    xmlWriter.writeElementString("PayeeBankName", (String) list.get(i).get("PayeeBankName"));
                }
                xmlWriter.writeEndElement();
            }
            xmlWriter.writeEndElement();
            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();//写入报文完成
            //发送给银行的签名端口进行签名
            String[] tmpSign = sendToBankFrontSign(xmlWriter.toXmlString());
            if (tmpSign[0].length() == 0) {
                String signature = "";
                String body = "";
                String aa = "<result>";
                int i = tmpSign[1].indexOf(aa);
                if (i != -1) {
                    body = tmpSign[1].substring(i + 8, i + 9);
                }
                if (body.equals("0")) {
                    String ab = "<sign>";
                    String ac = "</sign>";
                    int ib = tmpSign[1].indexOf(ab);
                    int ic = tmpSign[1].indexOf(ac);
                    //以下为最终的签名结果
                    signature = tmpSign[1].substring(ib + 6, ic);
                    singData = signature;
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    writeCommonHeader(xmlTextWriter, "1");
                    xmlTextWriter.writeStartElement("Body");
                    xmlTextWriter.writeElementString("PayerAcNo", p_reqBat.ownAct);
                    if (Integer.parseInt(p_reqBat.totalNum) <= 2000) {
                        xmlTextWriter.writeElementString("TotalCount", p_reqBat.totalNum);
                    } else {
                        retAts.respCode = "0";
                        retAts.respInfo = "批量支付最大支持总笔数不能超过2000笔";
                        retAts.reqSeqID = p_reqBat.reqBatchNO;
                        retAts.transState = PaymentState.FAIL_Batch;
                        retAts.payInfoCode = ConnState.FAIL;
                        retAts.writeRetToATS();
                        return retAts;
                    }
                    xmlTextWriter.writeElementString("TotalAmount", p_reqBat.totalAmt);
                    xmlTextWriter.writeElementString("CifJnlNo", reqHeader.reqSeqID);
                    if ("0".equals(p_reqBat.sameBnk)) {
                        String trsMode = "1";//默认人行大小额 暂不支持网银互联的方式
                        xmlTextWriter.writeElementString("Remit", trsMode);////1-大额2-网银互联
                    }
                    xmlTextWriter.writeStartElement("List");
                    for (int j = 0; j < list.size(); j++) {
                        xmlTextWriter.writeStartElement("Map");
                        xmlTextWriter.writeElementString("PayeeAcNo", (String) list.get(j).get("PayeeAcNo"));
                        xmlTextWriter.writeElementString("PayeeAcName", (String) list.get(j).get("PayeeAcName"));
                        xmlTextWriter.writeElementString("Amount", (String) list.get(j).get("Amount"));
                        xmlTextWriter.writeElementString("Remark", (String) list.get(j).get("Remark"));//传入对账码
                        xmlTextWriter.writeElementString("Use", (String) list.get(j).get("Use"));
                        xmlTextWriter.writeElementString("TraceNo", String.valueOf(j + 1));
                        if ("0".equals(p_reqBat.sameBnk)) {
                            xmlTextWriter.writeElementString("UnionDeptId", (String) list.get(j).get("UnionDeptId"));
                            xmlTextWriter.writeElementString("PayeeBankName", (String) list.get(j).get("PayeeBankName"));
                        }
                        xmlTextWriter.writeEndElement();
                    }
                    xmlTextWriter.writeEndDocument();//写入报文完成
                    String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());//发送银行
                    /*tmpStrRet[0] = "";
                      tmpStrRet[1] = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
					 "<Message>\n" +
					 " <Head>\n" +
					 "    <ReturnCode>000000</ReturnCode>\n" +
					 "    <ReturnMsg></ReturnMsg>\n" +
					 " </Head>\n" +
					 " <Body>\n" +
					 "    <IBSJnlNo>1849938</IBSJnlNo>\n" +
					 " </Body>\n" +
					 "</Message> ";*/
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        //解析银行返回
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<?xml")), tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                            String tmpInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                            if (tmpStatus != null && tmpStatus.length() > 0) {
                                retAts.respCode = "0";
                                retAts.reqSeqID = p_reqBat.reqBatchNO;
                                if (isActiveRetCode(tmpStatus)) {
                                    retAts.respInfo = tmpInfo;
                                    retAts.transState = tmpStatus;
                                    retAts.payInfoCode = retAts.transState;
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpSbMsg.toString();
                        }
                    } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpStrRet[1];
                        retAts.reqSeqID = p_reqBat.reqBatchNO;
                        retAts.transState = PaymentState.FAIL_Batch;
                        retAts.payInfoCode = tmpStrRet[0];
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStrRet[1];
                    }
                } else {//签名数据返回数据为空
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSign[1];
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSign[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.toString();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqBat.reqBatchNO;
        }
        retAts.writeRetToATS();
        return retAts;
    }

    //1998 状态查询
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    //9198
    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }

    //批量代付和工资代付状态查询
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        //返回ATS的对象
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.respCode = "";
        if ("1".equals(p_reqQryBat.sameBnk)) {//同行
            transCode = "B2EBatchInnerTransferResQry";
        } else if("0".equals(p_reqQryBat.sameBnk)){//跨行
            transCode = "B2EBatchTransferResQry";
        }
        String time1 = p_reqQryBat.bgnDate.substring(0, 10).replace("-", "");
        XmlTextWriter xmlWriter = null;
        xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        writeCommonHeader(xmlWriter, "0");//写入通用的头部节点
        xmlWriter.writeStartElement("Body");
        xmlWriter.writeElementString("CifJnlNo", retAts.retHeader.reqSeqID);
        xmlWriter.writeElementString("TransDate", time1);
        xmlWriter.writeEndElement();
        xmlWriter.writeEndDocument();
        try {
            //发送给银行的签名端口进行签名
            String[] tmpSign = sendToBankFrontSign(xmlWriter.toXmlString());
            if (tmpSign[0].length() == 0) {
                String signature = "";
                String body = "";
                String aa = "<result>";
                int i = tmpSign[1].indexOf(aa);
                if (i != -1) {
                    body = tmpSign[1].substring(i + 8, i + 9);
                }
                if (body.equals("0")) {
                    String ab = "<sign>";
                    String ac = "</sign>";
                    int ib = tmpSign[1].indexOf(ab);
                    int ic = tmpSign[1].indexOf(ac);
                    //以下为最终的签名结果
                    signature = tmpSign[1].substring(ib + 6, ic);
                    singData = signature;
                    XmlTextWriter xmlTextWriter = new XmlTextWriter();
                    writeCommonHeader(xmlTextWriter, "1");
                    xmlTextWriter.writeStartElement("Body");
                    xmlTextWriter.writeElementString("CifJnlNo", retAts.retHeader.reqSeqID);
                    xmlTextWriter.writeElementString("TransDate", time1);
                    xmlTextWriter.writeEndElement();
                    xmlTextWriter.writeEndDocument();
                    String[] tmpStrRet = sendToBank(xmlTextWriter.toXmlString());
                    if (tmpStrRet[0].length() == 0) {
                        StringBuilder tmpSbMsg = new StringBuilder();
                        XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1].substring(tmpStrRet[1].indexOf("<?xml")), tmpSbMsg);
                        if (tmpBkReader != null) {
                            String tmpStatus = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                            String tmpStatusText = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                            if (tmpStatus != null && tmpStatus.length() > 0) {
                                retAts.respCode = "0";
                                retAts.reqSeqID = p_reqQryBat.reqBatchNO;
                                int tmpCountRow = tmpBkReader.countElement("/Message/Body/TotalNum");
                                if (tmpCountRow > 0 && isActiveRetCode(tmpStatus)) {
                                    retAts.writeBeforeDetail();
                                    while (tmpBkReader.read("/Message/Body/List/Map")) {
                                        RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                        tmpRetDetail.recAct = tmpBkReader.readedXElement.getSingleText("PayeeAcNo");
                                        tmpRetDetail.recName = tmpBkReader.readedXElement.getSingleText("PayeeAcName");
                                        tmpRetDetail.payAmount = tmpBkReader.readedXElement.getSingleText("Amount");
                                        tmpRetDetail.usage = tmpBkReader.readedXElement.getSingleText("Use");
                                        tmpRetDetail.result = tmpStatus + "+" + tmpBkReader.readedXElement.getSingleText("Status");
                                        tmpRetDetail.postScript = tmpBkReader.readedXElement.getSingleText("Remark");//加入一个编号来确认这条记录信息
                                        tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                } else if (tmpCountRow == 0) {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = "状态查询结果为空";
                                } else {
                                    retAts.respCode = "-1";
                                    retAts.respInfo = tmpStatusText;
                                }
                            } else {
                                retAts.respCode = "-1";
                                retAts.respInfo = tmpStatusText;
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = tmpSbMsg.toString();
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = tmpStrRet[1];
                    }
                } else {//签名数据返回数据为空
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSign[1];
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpSign[1];
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
        }
        if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
            retAts.reqSeqID = p_reqQryBat.reqBatchNO;
        }
        if (retAts.respCode.equals("-1")) {
            retAts.writeBeforeDetail();
        }
        retAts.writeAfterDetail();
        return retAts;
    }

}
